package com.ganzi.ganziserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ganzi.ganziserver.core.*;
import com.ganzi.ganziserver.dao.UserDao;
import com.ganzi.ganziserver.service.SchoolInformationService;
import com.ganzi.ganziserver.service.UserService;
import com.ganzi.ganziserver.service.imp.SchoolInformationServiceImp;
import com.ganzi.ganziserver.shiro.redis.OtherCache.UserCache;
import com.ganzi.ganziserver.utils.GetTime;
import com.ganzi.ganziserver.utils.OtherException;
import com.ganzi.ganziserver.utils.PageBean;
import com.ganzi.ganziserver.utils.ReturnMap;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户操作controller
 * */
@RestController
@RequestMapping("/school")
public class SchoolController {
    private static Logger log = LoggerFactory.getLogger(SchoolController.class);

    @Autowired
    SchoolInformationService schoolInformationService;
    @Autowired
    UserCache cache;

    /**
     * 查看学校信息
     * */
//    @RequiresPermissions("getschool")
    @RequestMapping(value ="/schoolInformation",method = {RequestMethod.POST})
    public Object schoolInformation(){
        try{
            Subject subject = SecurityUtils.getSubject();
            User tempUser = cache.getUserByPrincipal();
            //具有所有权限 就可以查看所有学校
            boolean m = subject.isPermitted("allschool");
            if(m){
                List<SchoolInformation> schoolList = schoolInformationService.findAllSchoolInfoemation();
                return ReturnMap.getReturnMapData(200,"成功",schoolList);
            }else{
                List<Long> list = schoolInformationService.findSchoolByUserId(tempUser.getId());
                List<SchoolInformation> schoolList = new ArrayList<>();
                for(int a=0;a<list.size();a++){
                    SchoolInformation school = schoolInformationService.findSchoolInfoemationById(list.get(a));
                    if(school != null)schoolList.add(school);
                }
                return ReturnMap.getReturnMapData(200,"成功",schoolList);
            }
        }catch (Exception e){
            log.info("服务器异常：schoolInformation:"+e.getMessage());
            return ReturnMap.getReturnMap(400, "服务器异常");
        }
    }

    /**
     * 查看盘管信息
     * */
    @RequiresPermissions("getfan")
    @RequestMapping(value ="/fanInformation",method = {RequestMethod.POST})
    public Object fanInformation(@RequestBody String json){
        try{
            JSONObject jsons = (JSONObject) JSON.parse(json);
            long schoolId = jsons.getLongValue("schoolId");
            if(schoolId != 0l){
                List<FanInformation> fanList = schoolInformationService.findFanBySchoolId(schoolId);
                return ReturnMap.getReturnMapData(200, "成功",fanList);
            }
            return ReturnMap.getReturnMap(400, "学校不存在");
        }catch (Exception e){
            log.info("服务器异常：fanInformation:"+e.getMessage());
            return ReturnMap.getReturnMap(400, "服务器异常");
        }
    }


    /**
     * 添加盘管
     * */
    @RequiresPermissions("add")
    @RequestMapping(value ="/addFan",method = {RequestMethod.POST})
    public Object addFan(@RequestBody FanInformation fan){
        try{
            if(fan != null){
                if(fan.getCreateTime() == null){
                    fan.setCreateTime(GetTime.getNowTime());
                    fan.setId(0);
                }
                schoolInformationService.addFan(fan);
                return ReturnMap.getReturnMap(200, "添加成功");
            }
            return ReturnMap.getReturnMap(400, "输入信息不完整");
        }catch (OtherException e){
            return ReturnMap.getReturnMap(400, e.getMessage());
        }catch (Exception e){
            log.info("服务器异常：addFan:"+e.getMessage());
            return ReturnMap.getReturnMap(400, "服务器异常");
        }
    }

    /**
     * 修改盘管
     * */
    @RequiresPermissions("update")
    @RequestMapping(value ="/updateFan",method = {RequestMethod.POST})
    public Object updateFan(@RequestBody FanInformation fan){
        try{
            if(fan != null){
                if(fan.getCreateTime() == null)fan.setCreateTime(GetTime.getNowTime());
                schoolInformationService.updateFan(fan);
                return ReturnMap.getReturnMap(200, "修改成功");
            }
            return ReturnMap.getReturnMap(400, "输入信息不完整");
        }catch (Exception e){
            log.info("服务器异常：updateFan:"+e.getMessage());
            return ReturnMap.getReturnMap(400, "服务器异常");
        }
    }




    /**
     * 添加学校
     * */
    @RequiresPermissions("add")
    @RequestMapping(value ="/addSchool",method = {RequestMethod.POST})
    public Object addSchool(@RequestBody SchoolInformation school){
        try{
            if(school != null){
                if(school.getCreateTime() == null)school.setCreateTime(GetTime.getNowTime());
                schoolInformationService.addSchool(school);
                return ReturnMap.getReturnMap(200, "添加成功");
            }
            return ReturnMap.getReturnMap(400, "输入信息不完整");
        }catch (OtherException e){
            return ReturnMap.getReturnMap(400, e.getMessage());
        }catch (Exception e){
            log.info("服务器异常：addSchool:"+e.getMessage());
            return ReturnMap.getReturnMap(400, "服务器异常");
        }
    }

    /**
     * 修改学校
     * */
    @RequiresPermissions("update")
    @RequestMapping(value ="/updateSchool",method = {RequestMethod.POST})
    public Object updateSchool(@RequestBody SchoolInformation school){
        try{
            if(school != null){
                if(school.getCreateTime() == null)school.setCreateTime(GetTime.getNowTime());
                schoolInformationService.updateSchool(school);
                return ReturnMap.getReturnMap(200, "修改成功");
            }
            return ReturnMap.getReturnMap(400, "输入信息不完整");
        }catch (Exception e){
            log.info("服务器异常：updateSchool:"+e.getMessage());
            return ReturnMap.getReturnMap(400, "服务器异常");
        }
    }


    /**
     * 添加采集器
     * */
    @RequiresPermissions("add")
    @RequestMapping(value ="/addColletion",method = {RequestMethod.POST})
    public Object addColletion(@RequestBody FanCollect collect){
        try{
            if(collect != null){
                collect.setUpdateTime(GetTime.getNowTime());
                schoolInformationService.addCollection(collect);
                return ReturnMap.getReturnMap(200, "添加成功");
            }
            return ReturnMap.getReturnMap(400, "输入信息不完整");
        }catch (OtherException e){
            return ReturnMap.getReturnMap(400, e.getMessage());
        }catch (Exception e){
            log.info("服务器异常：addColletion:"+e.getMessage());
            return ReturnMap.getReturnMap(400, "服务器异常");
        }
    }

    /**
     * 查询学校
     * */
    @RequestMapping(value ="/findSchoolForCollection",method = {RequestMethod.POST})
    public Object findSchool(){
        try{
            Subject subject = SecurityUtils.getSubject();
            User tempUser = cache.getUserByPrincipal();
            boolean m = subject.isPermitted("allschool");
            List<TempSchool> temp = null;
            if(m){
                temp = schoolInformationService.getAllSchoolById(0);
            }else{
                List<Long> list = schoolInformationService.findSchoolByUserId(tempUser.getId());
                if(list != null && list.size()>0){
                    temp = new ArrayList<TempSchool>();
                    for(int a=0;a<list.size();a++){
                        List<TempSchool> listtemp = schoolInformationService.getAllSchoolById(list.get(a));
                        if(listtemp != null && listtemp.size()>0){
                            temp.add(listtemp.get(0));
                        }
                    }
                }
            }
            return ReturnMap.getReturnMapData(200, "服务器异常",temp);
        }catch (Exception e){
            log.info("服务器异常："+e.getMessage());
            return ReturnMap.getReturnMap(400, "服务器异常");
        }
    }

    /**
     * 查看采集器信息
     * */
    @RequiresPermissions("getcollection")
    @RequestMapping(value ="/collectionInformation",method = {RequestMethod.POST})
    public Object collectionInformation(@RequestBody String json){
        try{
            JSONObject jsons = null;
            int state = 0;
            int currentPage = 1;
            int pageSize = 100;
            if(StringUtils.isNotBlank(json))jsons= (JSONObject) JSON.parse(json);
            if(jsons != null && jsons.containsKey("state")){
                state = jsons.getIntValue("state");
            }
            if(jsons != null && jsons.containsKey("currentPage")){
                currentPage = jsons.getIntValue("currentPage");
            }
            if(jsons != null && jsons.containsKey("pageSize")){
                pageSize = jsons.getIntValue("pageSize");
            }
            PageHelper.startPage(currentPage, pageSize);
            List<FanCollect> cList = schoolInformationService.findCollection(state);
            int count = schoolInformationService.findCollectionCount(state);
            PageBean<FanCollect> pageData = new PageBean<>(currentPage, pageSize, count);
            pageData.setItems(cList);
            return ReturnMap.getReturnMapDataForPage(200, "成功",pageData.getItems(),pageData.getTotalPage(),pageData.getCurrentPage());
        }catch (Exception e){
            e.printStackTrace();
            log.info("服务器异常：fanInformation:"+e.getMessage());
            return ReturnMap.getReturnMap(400, "服务器异常");
        }
    }
}
